package com.sishu.njrtsdms.controller;

import cn.hutool.core.collection.CollUtil;
import com.sishu.njrtsdms.annotation.Anonymous;
import com.sishu.njrtsdms.domain.core.R;
import com.sishu.njrtsdms.jooq.codegen.tables.daos.SysFileDAO;
import com.sishu.njrtsdms.jooq.codegen.tables.pojos.SysFile;
import com.sishu.njrtsdms.service.SysFileService;
import com.sishu.njrtsdms.utils.StringUtils;
import com.sishu.njrtsdms.utils.file.FileUtils;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.*;

import java.util.List;

/**
 * 通用请求处理
 */
@RestController
@RequestMapping("/common")
@CrossOrigin
@Slf4j
public class CommonController {

    private final SysFileService sysFileService;

    private final SysFileDAO sysFileDAO;


    public CommonController(SysFileService sysFileService, SysFileDAO sysFileDAO) {
        this.sysFileService = sysFileService;
        this.sysFileDAO = sysFileDAO;
    }


    /**
     * 本地资源通用下载
     */
    @Anonymous
    @GetMapping("/downloadByUUID")
    public void downloadByUUID(@RequestParam("uuid") String uuid,
                               HttpServletRequest request,
                               HttpServletResponse response) {
        try {
            SysFile sysFile = sysFileDAO.fetchOneByUuid(uuid);
            if (sysFile == null)
                throw new RuntimeException("文件不存在或已被删除");
            String drivePath = sysFile.getDrivePath();
            String downloadName = StringUtils.substringAfterLast(drivePath, "/");
            response.setContentType(MediaType.APPLICATION_OCTET_STREAM_VALUE);
            FileUtils.setAttachmentResponseHeader(response, downloadName);
            FileUtils.writeBytes(drivePath, response.getOutputStream());
        } catch (Exception e) {
            log.error("下载文件失败", e);
        }
    }


    /**
     * 根据uuid列表删除文件
     */
    @Anonymous
    @DeleteMapping("/deleteFilesByUUIDs")
    public R<String> deleteFilesByUUIDs(@RequestBody List<String> UUIDList) {
        if (CollUtil.isNotEmpty(UUIDList))
            sysFileService.deleteFilesByUUIDs(UUIDList);
        return R.ok();
    }


}
